//
//  ZYComposeView.swift
//  WeiBo
//
//  Created by zhangyu on 16/10/5.
//  Copyright © 2016年 zhangyu. All rights reserved.
//

import UIKit
import pop

class ZYComposeView: UIView {
    
    private lazy var sloganImageView: UIImageView = UIImageView(image: UIImage(named:"compose_slogan"))
    
    //记录6个菜单按钮
    private lazy var buttonArray: [ZYComposeButton] = [ZYComposeButton]()
    private lazy var composeMenuArray: [ZYComposeMenu] = self.loadComposePlistData()
    //记录当前的控制器
    var target: UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = RandomColor()
        //获取模糊效果图片
        let image = UIImage.screenShot().applyLightEffect()
        let bgImageView = UIImageView(image: image)
        addSubview(bgImageView)
        addSubview(sloganImageView)
        
        sloganImageView.snp_makeConstraints { (make) in
            make.top.equalTo(self).offset(100)
            make.centerX.equalTo(self)
        }
        addChildButton()
//        startPopAnimation(isUp: true)
    }
    //开启弹簧动画效果
    private func startPopAnimation(isUp: Bool) {
        //如果是向下的弹簧动画，那么数组需要反转
        if isUp == false {
            buttonArray = buttonArray.reversed()
        }
        //遍历数组执行pop动画
        for (i, button) in buttonArray.enumerated() {
            let popAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            //目的地 ->toValue 不能直接穿入结构体，需要转化成对象
            if isUp {
                popAnimation?.toValue = NSValue(cgPoint: CGPoint(x:button.centerX, y: button.centerY - 350))
            } else {
                popAnimation?.toValue = NSValue(cgPoint: CGPoint(x:button.centerX, y:button.centerY + 350))
            }
            //动画的初始速度［0，20］
            popAnimation?.springSpeed = 10
            //抖动幅度
            popAnimation?.springBounciness = 10
            //开始动画的时间CACurrentMediaTime -> 系统的 绝对时间
            popAnimation?.beginTime = CACurrentMediaTime() + Double( i ) * 0.025
            //执行动画
            button.pop_add(popAnimation, forKey: nil)
        }
    }
    private func addChildButton() {
        let buttonWidth: CGFloat = 80
        let buttonHeight: CGFloat = 110
        let buttonMargin: CGFloat = (width - 3 * buttonWidth) / 4
        
        for i in 0..<composeMenuArray.count {
            let colIndex = i % 3
            let rowIndex = i / 3
            
            //获取指定下标的模型
            let composeMenu = composeMenuArray[i]
            
            let button = ZYComposeButton()
            //设置tag的值
            button.tag = i
            //添加点击事件
            button.addTarget(self, action: #selector(buttonAction(btn:)), for: .touchUpInside)
            
            button.x = CGFloat(colIndex) * buttonWidth + CGFloat(colIndex + 1) * buttonMargin
            button.y = CGFloat(rowIndex) * buttonHeight + CGFloat(rowIndex) * buttonMargin + ScreenHeight
            
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
//            button.setImage(UIImage(named: "tabbar_compose_idea"), for: .normal)
//            button.setTitle("文字", for: .normal)
            button.setImage(UIImage(named: composeMenu.icon!), for: .normal)
            button.setTitle(composeMenu.title!, for: .normal)
            addSubview(button)
            buttonArray.append(button)
        }
        
        
    }
// MARK: -- 点击事件处理
    @objc private func buttonAction(btn: UIButton) {
        UIView.animate(withDuration: 0.25, animations: { 
            for button in self.buttonArray {
                button.alpha = 0.2
                if button == btn {
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                } else {
                    button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
            }
            }) { (_) in
                UIView.animate(withDuration: 0.25, animations: { 
                    for button in self.buttonArray {
                        button.transform = CGAffineTransform.identity
                        button.alpha = 1
                    }
                    }, completion: { (_) in
//                        let composeVc = ZYComposeViewController()
//                        self.target?.present(composeVc, animated: true, completion: {
                            //移除罩层
//                            self.removeFromSuperview()
//                        })
                        /*
                         1.自定义的类直接无法通过类名转化成相应的class（解决办法：需要加上命名空间（工程名））
                         2.转化的class不可以直接初始化，需要转成相应的类型（类名.Type）
                         3.最后通过class转化为响应的对象
                        */
                        //获取指定模型
                        let composeMenu = self.composeMenuArray[btn.tag]
                        //获取对应的class
                        let classType = NSClassFromString(composeMenu.className!)! as! UIViewController.Type
                        let Vc = classType.init()
                        //vc放到导航控制器里面
                        let nav = ZYNavigationViewController(rootViewController: Vc)
                        self.target?.present(nav, animated: true, completion: {
                            self.removeFromSuperview()
                        })
                })
        }
    }
    func show(target: UIViewController) {
        self.target = target
        target.view.addSubview(self)
        //开启弹簧动画效果
        startPopAnimation(isUp: true)
    }
    //读取plist文件数据
    private func loadComposePlistData() -> [ZYComposeMenu] {
        //获取plist文件的路径
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        //获取plist文件中的路径
        let dicArray = NSArray(contentsOfFile: path)!
        let modelArray = NSArray.yy_modelArray(with: ZYComposeMenu.self, json: dicArray)! as! [ZYComposeMenu]
        return modelArray
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//        removeFromSuperview()
        startPopAnimation(isUp: false)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) { 
            self.removeFromSuperview()
        }
    }
}
